using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;

namespace Pavilion
{
    public class PlayerKeyboard : IKeyboard
    {
        public const string Name = "PlayerKeyboard";

        private List<Keys> keysPressed, keysReleased;

        public event Action<Keys[]> KeysPressed, KeysReleased;

        public PlayerKeyboard()
        {
            keysPressed = new List<Keys>();
            keysReleased = new List<Keys>();
        }

        public void Update(GameTime gameTime)
        {
            List<Keys> newKeys = new List<Keys>();
            newKeys.AddRange(Keyboard.GetState().GetPressedKeys());

            for (int i = 0; i < keysPressed.Count; i++)
            {
                if (Keyboard.GetState().IsKeyDown(keysPressed[i]))
                    newKeys.Remove(keysPressed[i]);
                else
                {
                    keysReleased.Add(keysPressed[i]);
                    keysPressed.Remove(keysPressed[i]);
                    i--;
                }
            }

            keysPressed.AddRange(newKeys.ToArray());

            if (newKeys.Count > 0)
                OnKeysPressed(newKeys.ToArray());

            if (keysReleased.Count > 0)
            {
                OnKeysReleased(keysReleased.ToArray());
                keysReleased.Clear();
            }

            ////Check for Keys Released
            //for (int i = 0; i < keysPressed.Count; i++)
            //{
            //    if (Keyboard.GetState().IsKeyUp(keysPressed[i]))
            //    {
            //        OnKeyReleased(keysPressed[i]);
            //        keysPressed.Remove(keysPressed[i]);
            //    }
            //}

            ////Check for Keys Pressed
            //for (int i = 0; i < keyList.Count; i++)
            //{
            //    if (Keyboard.GetState().IsKeyDown(keyList[i]) && !keysPressed.Contains(keyList[i]))
            //    {
            //        keysPressed.Add(keyList[i]);
            //        OnKeyPressed(keyList[i]);
            //    }
            //}
        }

        public bool GetKeyState(Keys key, bool isKeyDown)
        {
            if (isKeyDown)
            {
                if (Keyboard.GetState().IsKeyDown(key))
                    return true;
                else
                    return false;
            }
            else
            {
                if (Keyboard.GetState().IsKeyUp(key))
                    return true;
                else
                    return false;
            }
        }

        private void OnKeysPressed(Keys[] keys)
        {
            if (KeysPressed != null)
                KeysPressed(keys);
        }

        private void OnKeysReleased(Keys[] keys)
        {
            if (KeysReleased != null)
                KeysReleased(keys);
        }
    }
}
